package com.sd.repay.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.sd.repay.annotation.MerAuthStatusCheck;
import com.sd.repay.common.CommonResult;
import com.sd.repay.common.Constants;
import com.sd.repay.pojo.MerchantUser;
import com.sd.repay.utils.WebUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
public class MerAuthStatusCheckInterceptor extends HandlerInterceptorAdapter {
    private static Logger log = LoggerFactory.getLogger(MerAuthStatusCheckInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            //获得注解对象
            MerAuthStatusCheck merAuthStatusCheck = ((HandlerMethod) handler).getMethodAnnotation(MerAuthStatusCheck.class);
            Method method = ((HandlerMethod) handler).getMethod();

            String fullContentType = "application/json;charset=UTF8";
            response.setCharacterEncoding("UTF-8");
            response.setContentType(fullContentType);

            if (merAuthStatusCheck != null) {

                MerchantUser merchantUser = WebUtil.getCurrMerchantUser();
                if (null == merchantUser) {
                    response.getWriter().print(JSONObject.toJSONString(CommonResult.build(403, "请先登录")));
                    return false;
                }

                String merAuthStatus = merchantUser.getIsAuth();
                if (!Constants.MER_AUTH_STATUS_PASS.equals(merAuthStatus)) {
                    response.getWriter().print(JSONObject.toJSONString(CommonResult.build(403, "请先实名认证")));
                    return false;
                }
            }
        }
        return true;
    }

}
